Skip to content

chore: init plan validation schema#1092

Merged
adityachoudhari26 merged 2 commits intomainfrom
plan-validation-schema
Apr 30, 2026
Merged

chore: init plan validation schema#1092
adityachoudhari26 merged 2 commits intomainfrom
plan-validation-schema

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Apr 30, 2026

fixes #1088

Summary by CodeRabbit

Release Notes

  • New Features
    • Added policy-based validation framework for deployment plan targets with per-rule evaluation results.
    • Validation outcomes now capture pass/fail status, violation details, and evaluation timestamps for audit and compliance tracking.

Copilot AI review requested due to automatic review settings April 30, 2026 17:28
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 30, 2026

Warning

Rate limit exceeded

@adityachoudhari26 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 54 minutes and 28 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7c1e66b7-944f-4205-968b-d6c2f6f98b7a

📥 Commits

Reviewing files that changed from the base of the PR and between d8f6edf and c621247.

📒 Files selected for processing (1)
  • packages/db/src/schema/deployment-plan.ts
📝 Walkthrough

Walkthrough

This PR adds database schema and migrations for deployment plan validation results and OPA policy rules. It introduces two new tables (deploymentPlanTargetResultValidation and policyRulePlanValidationOpa) with their Drizzle ORM schema definitions, relations, and migration artifacts.

Changes

Cohort / File(s) Summary
Database Migration
packages/db/drizzle/0193_adorable_paibok.sql
Creates two new tables: policy_rule_plan_validation_opa storing OPA rego rules with policy association and metadata, and deployment_plan_target_result_validation capturing per-rule evaluation outcomes with passed status, violations (JSONB), and timestamp. Includes foreign key constraints with CASCADE deletion and indexes on foreign/unique key columns.
Migration Journal
packages/db/drizzle/meta/_journal.json
Records new migration entry (idx: 193) with tag 0193_adorable_paibok and timestamp.
TypeScript Schema
packages/db/src/schema/deployment-plan.ts
Introduces policyRulePlanValidationOpa table definition with policy reference and OPA rego content; adds deploymentPlanTargetResultValidation table with result/rule references, validation outcome, and typed violations; establishes bidirectional relations and unique constraint on (resultId, ruleId) pair. Updates deploymentPlanTargetResultRelations to expose validations relationship.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Possibly related PRs

  • init db #420 — Introduces the base policy schema that the new policyRulePlanValidationOpa table extends and references.

Poem

🐰 Two tables hop into the database so bright,
Validations and rules, a policy knight,
OPA rego flows, violations all caught,
Deployment plans now validate as they ought! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The policyRulePlanValidationOpa table was added to deployment-plan.ts instead of policy.ts as required by issue #1088. Move policyRulePlanValidationOpa and policyRulePlanValidationOpaRelations from deployment-plan.ts to policy.ts per the schema organization requirement in #1088.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'chore: init plan validation schema' accurately describes the main change: initializing database schema tables for plan validation.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the two tables, relations, migration, and journal entry specified in issue #1088.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch plan-validation-schema

Warning

Review ran into problems

🔥 Problems

Timed out fetching pipeline failures after 30000ms


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 54 minutes and 28 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Introduces the initial database schema needed to persist “plan validation” rules (OPA/Rego) and per-target validation results, as part of the DB layer for issue #1088.

Changes:

  • Adds policy_rule_plan_validation_opa and deployment_plan_target_result_validation tables to the Drizzle schema (plus relations from deploymentPlanTargetResult).
  • Adds a new Drizzle migration (0193_adorable_paibok.sql) and updates Drizzle metadata (journal + snapshot).

Reviewed changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 5 comments.

File Description
packages/db/src/schema/deployment-plan.ts Adds new plan-validation rule/result tables and wires relations from deployment plan target results.
packages/db/drizzle/0193_adorable_paibok.sql Creates the new tables, indexes, and foreign keys for the plan-validation schema.
packages/db/drizzle/meta/_journal.json Registers migration 0193_adorable_paibok in the Drizzle journal.
packages/db/drizzle/meta/0193_snapshot.json Captures the updated schema snapshot after adding the new tables.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +198 to +204
name: text("name").notNull(),
description: text("description"),
rego: text("rego").notNull(),
severity: text("severity").notNull(),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
Comment on lines +220 to +232

export const deploymentPlanTargetResultValidation = pgTable(
"deployment_plan_target_result_validation",
{
id: uuid("id").primaryKey().defaultRandom(),
resultId: uuid("result_id")
.notNull()
.references(() => deploymentPlanTargetResult.id, { onDelete: "cascade" }),
ruleId: uuid("rule_id").notNull(),
passed: boolean("passed").notNull(),
violations: jsonb("violations").$type<Violation[]>().notNull().default([]),
evaluatedAt: timestamp("evaluated_at", { withTimezone: true })
.notNull()
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "deployment_plan_target_result_validation" ADD CONSTRAINT "deployment_plan_target_result_validation_result_id_deployment_plan_target_result_id_fk" FOREIGN KEY ("result_id") REFERENCES "public"."deployment_plan_target_result"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
.notNull()
.references(() => deploymentPlanTargetResult.id, { onDelete: "cascade" }),
ruleId: uuid("rule_id").notNull(),
passed: boolean("passed").notNull(),
Comment on lines +191 to +199
export const policyRulePlanValidationOpa = pgTable(
"policy_rule_plan_validation_opa",
{
id: uuid("id").primaryKey().defaultRandom(),
policyId: uuid("policy_id")
.notNull()
.references(() => policy.id, { onDelete: "cascade" }),
name: text("name").notNull(),
description: text("description"),
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/db/src/schema/deployment-plan.ts`:
- Line 229: Change the bare UUID column declaration for ruleId into a proper FK
by making ruleId reference the rules table primary key (e.g., replace
uuid("rule_id").notNull() with a declaration that includes .references(...) /
foreign key to rules.id) so the DB enforces referential integrity; also ensure
the ORM relation defined around the existing relation block (the relation on
lines ~246-248) matches the FK, then regenerate the migration so the SQL
includes the rule_id foreign key constraint.
- Around line 191-207: The new table policyRulePlanValidationOpa is missing the
tenant-scoping workspaceId column; add a workspaceId field (e.g.,
uuid("workspace_id").notNull().references(() => workspace.id, { onDelete:
"cascade" })) to the pgTable definition, include it in the index tuple (e.g.,
(t) => [index().on(t.workspaceId), index().on(t.policyId)]) or a composite index
if desired, and apply the same change to the other new table(s) in this file
(the second pgTable block mentioned) so all tables include workspaceId for
multi-tenant isolation.
- Line 201: The column definition severity: text("severity").notNull() currently
allows any string; change it to a strict enum type and update imports so only
"error" or "warning" are permitted at the schema level (e.g., replace the text
column with a Postgres enum creation via pgEnum/enum helper or a DB-level check
constraint and import the enum helper). Update the symbol severity in
deployment-plan.ts to use that enum (and ensure the enum values are
["error","warning"]) so migrations/schemas enforce the allowed values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3824504e-081a-4302-adb7-47cb064b7f74

📥 Commits

Reviewing files that changed from the base of the PR and between 4624748 and d8f6edf.

📒 Files selected for processing (4)
  • packages/db/drizzle/0193_adorable_paibok.sql
  • packages/db/drizzle/meta/0193_snapshot.json
  • packages/db/drizzle/meta/_journal.json
  • packages/db/src/schema/deployment-plan.ts

Comment on lines +191 to +207
export const policyRulePlanValidationOpa = pgTable(
"policy_rule_plan_validation_opa",
{
id: uuid("id").primaryKey().defaultRandom(),
policyId: uuid("policy_id")
.notNull()
.references(() => policy.id, { onDelete: "cascade" }),
name: text("name").notNull(),
description: text("description"),
rego: text("rego").notNull(),
severity: text("severity").notNull(),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => [index().on(t.policyId)],
);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

New tables are missing workspaceId for tenant isolation.

Both newly added tables omit a workspaceId column, which weakens direct tenant scoping and violates the repository’s multi-tenant schema rule.

As per coding guidelines **/packages/db/**/*.ts: All database tables include workspaceId for multi-tenant isolation.

Also applies to: 222-237

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/db/src/schema/deployment-plan.ts` around lines 191 - 207, The new
table policyRulePlanValidationOpa is missing the tenant-scoping workspaceId
column; add a workspaceId field (e.g.,
uuid("workspace_id").notNull().references(() => workspace.id, { onDelete:
"cascade" })) to the pgTable definition, include it in the index tuple (e.g.,
(t) => [index().on(t.workspaceId), index().on(t.policyId)]) or a composite index
if desired, and apply the same change to the other new table(s) in this file
(the second pgTable block mentioned) so all tables include workspaceId for
multi-tenant isolation.

name: text("name").notNull(),
description: text("description"),
rego: text("rego").notNull(),
severity: text("severity").notNull(),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Constrain severity to allowed values at schema level.

Line 201 currently accepts any text; this should be restricted to "error" or "warning" to prevent invalid rule configurations entering the DB.

Suggested fix
+export const policyRulePlanValidationSeverity = pgEnum(
+  "policy_rule_plan_validation_severity",
+  ["error", "warning"],
+);

 export const policyRulePlanValidationOpa = pgTable(
   "policy_rule_plan_validation_opa",
   {
@@
-    severity: text("severity").notNull(),
+    severity: policyRulePlanValidationSeverity("severity").notNull(),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/db/src/schema/deployment-plan.ts` at line 201, The column definition
severity: text("severity").notNull() currently allows any string; change it to a
strict enum type and update imports so only "error" or "warning" are permitted
at the schema level (e.g., replace the text column with a Postgres enum creation
via pgEnum/enum helper or a DB-level check constraint and import the enum
helper). Update the symbol severity in deployment-plan.ts to use that enum (and
ensure the enum values are ["error","warning"]) so migrations/schemas enforce
the allowed values.

resultId: uuid("result_id")
.notNull()
.references(() => deploymentPlanTargetResult.id, { onDelete: "cascade" }),
ruleId: uuid("rule_id").notNull(),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add the missing foreign key on ruleId.

Line 229 defines ruleId as a bare UUID, so the DB can store validation rows pointing to non-existent rules. The relation on Lines 246-248 is ORM-level only and does not enforce referential integrity.

Suggested fix
 export const deploymentPlanTargetResultValidation = pgTable(
   "deployment_plan_target_result_validation",
   {
@@
-    ruleId: uuid("rule_id").notNull(),
+    ruleId: uuid("rule_id")
+      .notNull()
+      .references(() => policyRulePlanValidationOpa.id, { onDelete: "cascade" }),

After this, regenerate the migration so SQL includes the rule_id FK.

Also applies to: 246-248

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/db/src/schema/deployment-plan.ts` at line 229, Change the bare UUID
column declaration for ruleId into a proper FK by making ruleId reference the
rules table primary key (e.g., replace uuid("rule_id").notNull() with a
declaration that includes .references(...) / foreign key to rules.id) so the DB
enforces referential integrity; also ensure the ORM relation defined around the
existing relation block (the relation on lines ~246-248) matches the FK, then
regenerate the migration so the SQL includes the rule_id foreign key constraint.

@adityachoudhari26 adityachoudhari26 merged commit 32bde8e into main Apr 30, 2026
20 checks passed
@adityachoudhari26 adityachoudhari26 deleted the plan-validation-schema branch April 30, 2026 17:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

schema: plan validation rules + results tables

2 participants